<?php
namespace  App\Dao\Mongo;
use App\Models\Mongo\Server\AdminsDir AS AdminsDirModel;
use App\Common\Helper;
use MongoDB\BSON\ObjectId;
use  App\Common\Http\Basics\Upload;
class AdminsDir extends BaseMongo
{

    const params = [
        'dir_name',
        'dir_sort',
        'dir_pid',
        'dir_link'
    ];

    public static function create(string $admins_id, int $is_common)
    {
        //0代表非公共 1代表公共
        return $is_common === 0 ? AdminsDirModel::create(substr($admins_id, 0, 1)) : AdminsDirModel::create();
    }

    public static function add(string $admins_id,int $is_common ,array $params)
    {
        if($params['dir_pid'] == 0) $params['dir_link']  = "";
        else {
           $res =  self::create($admins_id, $is_common)->findOne(['admins_id' => $admins_id,'_id' => new ObjectId($params['dir_pid'])] ,
           [
            'projection' => [
                "_id" => [
                '$toString' =>  '$_id'
                ] ,
                "dir_link" => 1
            ]
           ]);

           if(!$res) return Upload::P_DIR_NOT_DEFINED;

           if(  $res->dir_link !== "" )  return Upload::DIR_MORE_TWO_LEVE;

           $params['dir_link'] = ($res->dir_link === "" ? $res->_id :  $res->dir_link . ",". $res->_id)  ;

        }
        // =  ? "" :   ;
        return self::create($admins_id , $is_common)->insertOne( array_merge( Helper::formExtractData($params,self::params) , [ 'admins_id' => $admins_id ] ) )->getInsertedId();
    }

    public static function delete(string $admins_id, int $is_common, array $ids)
    {
        return self::create($admins_id, $is_common)->deleteMany(['admins_id' => $admins_id ,
        '$or' =>
          array_map(function($item){
              return ['_id' =>new ObjectId($item) ];
          },$ids)
          ]);
    }


    public static function edit(string $admins_id, int $is_common, array $params)
    {
        return self::create($admins_id, $is_common)->updateOne(['admins_id' => $admins_id, '_id' => new ObjectId($params['dir_id'])], ['$set' => Helper::formExtractData($params, ['dir_name','dir_sort'])]);
    }



    public static function all(string $admins_id, int $is_common){
        $arr = [];
        foreach ( self::create($admins_id, $is_common)->find([
            'admins_id' => $admins_id
        ], [
            'sort' => ['dir_sort' => -1],
            'projection' => [
                "dir_name" => 1,
                "admins_id" => 1,
                "dir_link" => 1,
                "dir_sort" => 1,
                "dir_pid" => 1,
                "_id" => 0 ,
                "dir_id" => [
                    '$toString' =>  '$_id'
                ],
            ]
        ]) as $val){
            $val->dir_pid = (string) $val->dir_pid;
            $arr[] =   (array)$val;
        }
        return $arr;
    }


}
